package com.mjk.common.tools.encrypt;



import com.mjk.common.tools.logger.BizLogger;

import java.io.*;

public class Base64Utils {
	private  Base64Utils() {}
	private static final int CACHE_SIZE = 1024;

	public static byte[] decode(String base64)  {
		return Base64.decode(base64.getBytes());
	}

	public static String encode(byte[] bytes)  {
		return Base64.encode(bytes);
	}

	public static String encodeFile(String filePath)  {
		byte[] bytes = fileToByte(filePath);
		return encode(bytes);
	}

	public static void decodeToFile(String filePath, String base64)
			 {
		byte[] bytes = decode(base64);
		byteArrayToFile(bytes, filePath);
	}

	public static byte[] fileToByte(String filePath){
		byte[] data;
		File file = new File(filePath);
		if (file.exists()) {
			try(
					FileInputStream	in = new FileInputStream(file);
					ByteArrayOutputStream out = new ByteArrayOutputStream(2048)
            ) {

				byte[] cache = new byte[CACHE_SIZE];
				int nRead;
				while ((nRead = in.read(cache)) != -1) {
					out.write(cache, 0, nRead);
					out.flush();
				}
				data = out.toByteArray();
				return data;
			}catch(Exception e) {
				BizLogger.error(e);
			}
		}
		return new byte[0];
	}

	public static void byteArrayToFile(byte[] bytes, String filePath) {

		try(
				InputStream in = new ByteArrayInputStream(bytes);
				OutputStream out = new FileOutputStream(filePath)
        ) {
			File destFile = new File(filePath);
			if (!destFile.getParentFile().exists()) {
				destFile.getParentFile().mkdirs();
			}
			if(destFile.createNewFile()) {
				byte[] cache = new byte[CACHE_SIZE];
				int nRead;
				while ((nRead = in.read(cache)) != -1) {
					out.write(cache, 0, nRead);
					out.flush();
				}
			}
		}catch(Exception e) {
			BizLogger.error(e);
		}
	}
}